﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Manage_EditForum : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            TreasurerDataContext db = new TreasurerDataContext();

            #region 加载栏目信息
            var q = from aF in db.Forums
                    select aF;
            ListItem li = new ListItem("请选择", "-");
            ForumList.Items.Add(li);
            foreach (Forums f in q)
            {
                li = new ListItem(f.Name, f.ID);
                ForumList.Items.Add(li);
            }
            #endregion

            string id = Request.Params["fid"];
            if (id != null && id != "")
            {
                q = q.Where(aF => aF.ID == id);

                if (q.Count() > 0)
                {
                    Forums f = q.First();
                    IDText.Value = f.ID;
                    NameText.Text = f.Name;
                    DescriptionText.Text = f.Description;

                    if (f.ParentID != null)
                    {
                        ForumList.SelectedValue = f.ParentID;
                    }
                }
            }
        }
    }
    protected void SaveButton_Click(object sender, EventArgs e)
    {
        string id = IDText.Value.Trim();
        string name = NameText.Text.Trim();
        string description = DescriptionText.Text.Trim();
        string parentId = ForumList.SelectedValue;

        Forums f;
        TreasurerDataContext db = new TreasurerDataContext();

        var q = from aF in db.Forums
                where aF.Name == name
                select aF;

        if (q.Count() > 0)
        {
            f = q.First();
            if (id == "" || f.ID != id)
            {
                ErrorText.Text = "栏目名称已经存在。";
                return;
            }
        }


        if (id == "")
        {
            f = new Forums();
            f.ID = Toolkit.NextId();
            db.Forums.InsertOnSubmit(f);
        }
        else
        {
            f = (from aF in db.Forums
                 where aF.ID == id
                 select aF).First();
        }

        f.Name = name;
        f.Description = description;

        if (parentId == "-")
        {
            f.ParentID = null;
        }
        else
        {
            f.ParentID = parentId;
        }

        db.SubmitChanges();

        Response.Write("<script>alert('栏目信息保存成功。');document.location='./ListForums.aspx';</script>");
    }
}